package com.yunsoft.gateway.interceptor.handler;

import com.alibaba.fastjson.JSON;
import com.fld.central.common.model.protocol.ResultDto;
import com.fld.platform.commons.dto.PageDto;
import java.util.Collection;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseBodyHandler implements ResponseBodyAdvice<Object> {

	public static final String RESPONSE_BODY = "RESPONSE_BODY";
	
	@Override
	public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
		return true;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
			Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
			ServerHttpResponse response) {
		if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest req = (ServletServerHttpRequest) request;
			StringBuilder builder = new StringBuilder("");
			if (body instanceof ResultDto) {
				ResultDto result = (ResultDto)body;
				Object data = result.getData();
				if (data instanceof Collection) {
					builder.append("数据长度"+((Collection)data).size());
				} else if (data instanceof PageDto) {
					builder.append("分页数据"+((PageDto)data).toString());
				} else {
					builder.append(JSON.toJSONString(body));
				}
			} else {
				builder.append(JSON.toJSONString(body));
			}
			req.getServletRequest().setAttribute(RESPONSE_BODY, builder.toString());
		}
		return body;
	}

}
